/*
 * Created on 2006-2-25
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.toyi.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yangbingxp
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class ChangePasswordServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		List errors = new ArrayList();
		checkUI(req, errors);
		if (errors.size() == 0) {
			UserInfo user = ToyiSecurityManager.getUserInfo(req);
			if (user != null) {
				user.setPassword(req.getParameter("newPassword").trim());
				UserInfoManager.saveUserInfo(user);
				req.getRequestDispatcher("changepasswordok.jsp").forward(req,
						res);
			}
		} else {
			req.setAttribute("error", errors);
			req.getRequestDispatcher("changepassword.jsp").forward(req, res);
		}
	}

	private void checkUI(HttpServletRequest req, List errors) {
		String oldPassword = req.getParameter("oldPassword").trim();
		String newPassword = req.getParameter("newPassword").trim();
		String truePassword = ToyiSecurityManager.getUserInfo(req)
				.getPassword();
		if (!oldPassword.equals(truePassword)) {
			errors.add("\"oldtrue\"");
		} else {
			if (oldPassword.equals(newPassword)) {
				errors.add("\"oldnew\"");
			}
		}
	}
}